﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AssetsPoolManager : MonoSingleton<AssetsPoolManager>
{
    private int InfoToHash(string s1, string s2)
    {
        int hashCode = 1686112577;
        hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(s1);
        hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(s2);
        return hashCode;
    }
    // key: <bundleName, assetName> -> hashCode
    // value: [GameObject]
    private Dictionary<int, List<GameObject>> dicCache = new Dictionary<int, List<GameObject>>();
    
    public void Collection<T>(GameObject inObject) where T : UIBase
    {
        // add to cache
        inObject.transform.SetParent(transform, false);
        inObject.SetActive(false);
        UIAssetInfoAttribute info = Utils.GetAttributeInfo<T>();
        if(null == info) {
            Debug.LogErrorFormat("AssetPoolManager.Collection<{0}>, UIAssetInfoAttribute not registe...", typeof(T));
            return;
        }
        int key = InfoToHash(info.BundelName, info.AssetName);
        if (!dicCache.ContainsKey(key)) {
            dicCache.Add(key, new List<GameObject>(4));
        }
        dicCache[key].Add(inObject);
    }

    public void ClearCache()
    {
        foreach(var pair in dicCache) {
            List<GameObject> list = pair.Value;
            for(int i=0; i<list.Count; i++) {
                Destroy(list[i]);
            }
            list.Clear();
        }
    }

    public GameObject LoadAsset<T>() where T : UIBase
    {
        UIAssetInfoAttribute info = Utils.GetAttributeInfo<T>();
        if (null == info) {
            Debug.LogErrorFormat("AssetPoolManager.Collection<{0}>, UIAssetInfoAttribute not registe...", typeof(T));
            return null;
        } else {
            return LoadAsset(info.BundelName, info.AssetName);
        }
    }

    public GameObject LoadAsset(string bundleName, string assetName)
    {
        GameObject instantiateObject = GetAssetFromCache(bundleName, assetName);
        if (null == instantiateObject) {
            GameObject asset = AssetsLoadManager.Instance.LoadAsset<GameObject>(bundleName, assetName);
            instantiateObject = Instantiate<GameObject>(asset);
        }
        instantiateObject.SetActive(true);
        return instantiateObject;
    }

    private GameObject GetAssetFromCache(string bundleName, string assetName)
    {
        GameObject ret = null;
        int hashCode = InfoToHash(bundleName, assetName);
        if (dicCache.ContainsKey(hashCode) && dicCache[hashCode].Count > 0) {
            ret = dicCache[hashCode][0];
        }
        return ret;
    }

}
